package com.ganzi.ganziserver.rabbit.send;

import com.ganzi.ganziserver.core.FanCollect;
import com.ganzi.ganziserver.dao.FanCollectDao;
import com.ganzi.ganziserver.dao.SchoolInformationDao;
import com.ganzi.ganziserver.service.SendService;
import com.ganzi.ganziserver.service.imp.QueryThreadServiceImp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendQueryThread extends Thread{
    private static Logger log = LoggerFactory.getLogger(SendQueryThread.class);
    private SendService sendService = null;
    private SchoolInformationDao schoolDao = null;
    private FanCollectDao collectDao = null;
    private long schoolId;
    private long collectId;
    private String channelName;
    private int gapTime = 0;
    private volatile boolean canRun = true;

    public SendQueryThread(SendService send,FanCollectDao collectDao,SchoolInformationDao schoolDao,long schoolId,String channelName,long collectId,int gapTime){
        this.sendService = send;
        this.collectDao = collectDao;
        this.schoolDao = schoolDao;
        this.schoolId = schoolId;
        this.channelName = channelName;
        this.collectId = collectId;
        this.gapTime = gapTime;
    }
    @Override
    public void run() {
        try {
            String key = channelName+collectId;
            if(sendService != null && collectDao!=null && schoolDao!=null){
                while(!isInterrupted() && canRun){
                    Integer onLine = schoolDao.findSchoolOnlineById(schoolId);
                    //学校在线才发送
                    if(onLine != null && onLine == 1){
                        FanCollect collect = collectDao.findFanCollectById(collectId);
                        sendService.sendQueryForCollection(channelName,collect.getIp(),Integer.parseInt(collect.getAllCount()));
                    }else{
                        break;
                    }
                    if(gapTime == 0)gapTime=30;
                    Thread.sleep(1000*60*gapTime);
                }
                clear(key);
            }else{
                clear(key);
            }
        }catch (Exception e){
            clear(channelName+collectId);
        }
    }


    public void clear(String key){
        synchronized(QueryThreadServiceImp.collectionQueue){
            QueryThreadServiceImp.collectionQueue.remove(key);
        }
        interrupt();
        this.canRun = false;
        log.info("删除查询线程："+key+" 剩余线程数："+QueryThreadServiceImp.collectionQueue.size());
    }


    public void setCanRun(boolean canRun){
        this.canRun = canRun;
    }
}
